package org.lds.ers.client.widgets;

import java.util.List;

import org.lds.ers.client.MyInfo;
import org.lds.ers.client.StakeService;
import org.lds.ers.client.StakeServiceAsync;
import org.lds.ers.client.WardService;
import org.lds.ers.client.WardServiceAsync;
import org.lds.ers.client.model.StakeERSCInfo;
import org.lds.ers.client.model.StakeInfo;
import org.lds.ers.client.model.WardERSCInfo;
import org.lds.ers.client.model.WardInfo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class MaintainWard extends VerticalPanel {
	private static MaintainWard singleton;
	public static MaintainWard getInstance()
	{
		if (singleton==null)
			singleton = new MaintainWard();
		
		return singleton;
	}
	
	final private Label lblBanner;
	final private VerticalPanel pnl1;
	final private ListBox cboStake; 
	final private VerticalPanel pnlWardList;
	final private TextBox txtWardName;
	final private TextBox txtWardNo;
	final private TextBox txtRemark;

	final Button btnAdd ;
	
	private StakeServiceAsync stakeService = GWT.create(StakeService.class);
	private WardServiceAsync wardService = GWT.create(WardService.class);
	
	private MaintainWard()
	{
		this.lblBanner = new Label("[[管理支會]]");
		this.add(this.lblBanner);
		//this.self = this;
		this.pnl1 = new VerticalPanel();
		this.add(pnl1);
		
		this.pnl1.add(new Label("選擇支聯會："));
		//Add ComboBox
		cboStake = new ListBox(false);
		cboStake.addChangeHandler(new ChangeHandler() {

			public void onChange(ChangeEvent event) {
				// TODO Auto-generated method stub
				refreshWards();
			}
			
		});
		this.pnl1.add(cboStake);
		//Add panel for Ward list
		pnlWardList = new VerticalPanel();
		this.pnl1.add(pnlWardList);
		
		//Add a panel for insert new ERS records.
		final DecoratorPanel pnlAddNew = new DecoratorPanel();
		pnlAddNew.setVisible(false);
		
		btnAdd = new Button("儲存");
		btnAdd.setEnabled(false);
		
		FlexTable editForm = new FlexTable();
		editForm.setWidget(0, 0, new Label("支分會名稱 :"));
		this.txtWardName = new TextBox();
		this.txtWardName.addKeyPressHandler(new KeyPressHandler(){
			public void onKeyPress(KeyPressEvent event) {
				boolean isEnable = !txtWardName.getText().equals("");
				btnAdd.setEnabled(isEnable);
				//btnAdd.setEnabled(!txtWardName.getText().equals(""));
				
			}
		});
		editForm.setWidget(0,1,this.txtWardName);
		
		editForm.setWidget(1, 0, new Label("支分會編號 :"));
		this.txtWardNo = new TextBox();
		editForm.setWidget(1,1,this.txtWardNo);

		editForm.setWidget(2, 0, new Label("備註 :"));
		this.txtRemark = new TextBox();
		editForm.setWidget(2,1,this.txtRemark);
		
		btnAdd.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				btnAdd.setEnabled(false);
				if (cboStake.getSelectedIndex() > -1)
				{
					WardInfo ward = new WardInfo();
					ward.setWardName(txtWardName.getText());
					ward.setWardNo(txtWardNo.getText());
					ward.setRemark(txtRemark.getText());
					ward.setByWhom(MyInfo.get().getEmailAddress());
					ward.setStakeID(Long.parseLong(cboStake.getValue(cboStake.getSelectedIndex())));
				
					wardService.insert(ward, new AsyncCallback<WardInfo>() {

						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							btnAdd.setEnabled(true);
							Window.alert(caught.getMessage());
						}

						public void onSuccess(WardInfo result) {
							// TODO Auto-generated method stub
							txtWardName.setText("");
							txtWardNo.setText("");
							txtRemark.setText("");
							btnAdd.setEnabled(false);
							pnlAddNew.setVisible(false);
							refreshWards();
							MaintainWardERS.getInstance().refreshWard();
						}
				    });
				}
			}
		});
		
		editForm.setWidget(1,2, btnAdd);
		final Button btnCancel = new Button("取消");
		btnCancel.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				pnlAddNew.setVisible(false);
				txtWardName.setText("");
				txtWardNo.setText("");
				txtRemark.setText("");
				btnAdd.setEnabled(false);
			}
		});
		
		editForm.setWidget(1,3,btnCancel);
		pnlAddNew.add(editForm);
		
		final Button btnShowAddNew = new Button("新增");
		btnShowAddNew.addClickHandler(new ClickHandler(){

			public void onClick(ClickEvent event) {
				pnlAddNew.setVisible(true);
			}
		});
		
		this.pnl1.add(btnShowAddNew);
		this.pnl1.add(pnlAddNew);
		
		refreshStakes();
		refreshWards();
	}
	
	public void refreshStakes()
	{
		stakeService.getAll(new AsyncCallback<List<StakeInfo>>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert(caught.getMessage());
			}

			public void onSuccess(List<StakeInfo> result) {
				// TODO Auto-generated method stub
				cboStake.clear();
				for(StakeInfo s : result) {
					cboStake.addItem(s.getStakeName() + "(" + s.getStakeNo() + ")", s.getId() + "");
				}
				if (result.size() > 0)
					cboStake.setItemSelected(0, true);
				refreshWards();
			}
	    });
	}
	public void refreshWards()
	{
		if (this.cboStake.getSelectedIndex() == -1)
			return ;
		Long stakeID = Long.parseLong(this.cboStake.getValue(this.cboStake.getSelectedIndex()));
		wardService.getAll(stakeID, new AsyncCallback<List<WardInfo>>() {

			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}

			public void onSuccess(List<WardInfo> result) {
				pnlWardList.clear();
				final FlexTable flexTable =new FlexTable();
			    
			    flexTable.addStyleName("cw-FlexTable");
			    flexTable.setWidth("32em");
			    flexTable.setBorderWidth(1);
			    flexTable.setCellSpacing(0);
			    flexTable.setCellPadding(3);
			    flexTable.setText(0, 0, "支會名稱：" );
				flexTable.setText(0, 1, "支會代碼：" );
				flexTable.setText(0,4,"StakeName");
				flexTable.setText(0, 2, "備註");
				flexTable.setText(0, 3, "");
			    
			    int row = 1;
				for(WardInfo s : result )
				{
					addRow(row, flexTable, s);
					row += 1;
				}
				pnlWardList.add(flexTable);
				
			}
	    });	
	}
	
	private void addRow(int row, FlexTable table, WardInfo info)
	{
		final WardInfo ward = info;
		table.setText(row, 0, ward.getWardName() );
		table.setText(row, 1, ward.getWardNo() );
		table.setText(row, 2, ward.getRemark());
		table.setText(row, 4, ward.getStakeName());
		
		final Button btnDelete = new Button("移除");
		btnDelete.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (Window.confirm("您確定要移除這位支分會『" + ward.getWardName() + "(" +  ward.getWardNo()  + ")』"))
				{
					btnDelete.setEnabled(false);
					wardService.delete(ward.getId(), new AsyncCallback<Boolean>() {
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							btnDelete.setEnabled(true);
							Window.alert(caught.getMessage());
						}

						public void onSuccess(Boolean result) {
							
							refreshWards();
						}
				    });
				}
			}
		});
		
		table.setWidget(row, 3, btnDelete );
	}
	
}
